package com.csl.testjetpack.data.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.csl.testjetpack.data.bean.RemoteButtonInfo
import com.csl.testjetpack.data.bean.RemoteInfo
import com.csl.testjetpack.data.dao.RemoteDao

/**
 * 数据库类
 * 1. 继承RoomDatabase
 * 2. 注释中添加关联表 entities
 * 3. 存在无参构造器, 并且返回使用@Dao注释的对象方法 abstract val remoteDao: RemoteDao?
 * (kotlin 自带get set, 故合法)
 */
@Database(
    entities = [RemoteInfo::class, RemoteButtonInfo::class, ],
    version = 3,
    exportSchema = true
)
abstract class RemoteDatabase : RoomDatabase() {
    abstract val remoteDao: RemoteDao?


    companion object {
        private const val DB_NAME = "RemoteDatabase.db"

        // For Singleton instantiation
        @Volatile
        private var instance: RemoteDatabase? = null
        fun getDatabase(context: Context): RemoteDatabase {
            return instance ?: synchronized(this) {
                instance ?: create(context).also { instance = it }
            }
        }

        fun close() {
            instance?.close()
        }

        private fun create(context: Context): RemoteDatabase {
            return Room.databaseBuilder(
                context,
                RemoteDatabase::class.java,
                DB_NAME
            ).fallbackToDestructiveMigration()
                .build()
        }


    }


}